package com.yunhai.store.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunhai.common.dto.GlobalException;
import com.yunhai.common.dto.PaginationVo;
import com.yunhai.common.utils.ObjectUtil;
import com.yunhai.common.utils.ReflectionCopy;
import com.yunhai.model.entity.tms.TmsStoreGroupEntity;
import com.yunhai.model.vo.tms.TmsStoreGroupBatchAddVo;
import com.yunhai.model.vo.tms.TmsStoreGroupQuery;
import com.yunhai.model.vo.tms.TmsStoreGroupVo;
import com.yunhai.store.listener.TmsStoreGroupListener;
import com.yunhai.store.mapper.TmsStoreGroupMapper;
import com.yunhai.store.service.TmsStoreGroupService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class TmsStoreGroupServiceImpl implements TmsStoreGroupService {

    @Resource
    private TmsStoreGroupMapper tmsStoreGroupMapper;
    @Resource
    private FmsCodeDictServiceImpl fmsCodeDictService;


    /**
     * 获取 TmsStoreGroup 分页列表
     */
    @Transactional
    public IPage getTmsStoreGroupPagination(PaginationVo paginationVo, TmsStoreGroupQuery tmsStoreGroupQuery ) throws Exception {

        IPage page = new Page( paginationVo.getPageIndex(), paginationVo.getPageSize() );
        LambdaQueryWrapper<TmsStoreGroupEntity> lqs = new LambdaQueryWrapper();
        lqs.likeRight(tmsStoreGroupQuery.getName() !=null, TmsStoreGroupEntity::getName, tmsStoreGroupQuery.getName());
        lqs.likeRight(tmsStoreGroupQuery.getParentId() !=null, TmsStoreGroupEntity::getParentId, tmsStoreGroupQuery.getParentId());
        tmsStoreGroupMapper.selectPage(page, lqs);

        List<TmsStoreGroupEntity> record = page.getRecords();
        if( !ObjectUtil.isNotEmptyList(record)){
            return page;
        }
        return page;
    }


    /**
     * 获取 TmsStoreGroup 所有数据
    */
    @Transactional
    public List<TmsStoreGroupEntity> getTmsStoreGroupAllList( TmsStoreGroupQuery tmsStoreGroupQuery ) throws Exception {

        LambdaQueryWrapper<TmsStoreGroupEntity> lqs = new LambdaQueryWrapper();
        List<TmsStoreGroupEntity> list = tmsStoreGroupMapper.selectList(lqs);
        //过滤掉没有下级区域的 storegroup


        return list;
    }


    /**
     * 获取 TmsStoreGroup 详情
    */
    @Transactional
    public TmsStoreGroupEntity getTmsStoreGroupDetail( Long id) throws Exception {

        TmsStoreGroupEntity tmsStoreGroup = tmsStoreGroupMapper.selectById(id);
        return tmsStoreGroup;
    }


    /**
     * 新增 TmsStoreGroup
     * */
    @Transactional
    public TmsStoreGroupEntity addTmsStoreGroup(TmsStoreGroupVo tmsStoreGroupVo) throws Exception {

        TmsStoreGroupEntity tmsStoreGroup = new TmsStoreGroupEntity();
        ReflectionCopy.copyProperties( tmsStoreGroup, tmsStoreGroupVo );
        tmsStoreGroupMapper.insert(tmsStoreGroup);

        fmsCodeDictService.updateById(8L, tmsStoreGroupVo.getNumber());
        return tmsStoreGroup;
    }


    /**
     * 更新 TmsStoreGroup
     * */
    @Transactional
    public void updateTmsStoreGroup( TmsStoreGroupVo tmsStoreGroupVo) throws Exception {

        if( tmsStoreGroupVo.getId() == null ){
            throw GlobalException.gen(10021, "id不存在");
        }
        TmsStoreGroupEntity tmsStoreGroup = new TmsStoreGroupEntity();
        ReflectionCopy.copyProperties( tmsStoreGroup, tmsStoreGroupVo );
        tmsStoreGroupMapper.updateById(tmsStoreGroup);
        return;
    }

    /**
     * 删除 TmsStoreGroup
     * */
    @Transactional
    public void batchRemoveTmsStoreGroup( List<Long> ids ) throws Exception {

        /**
         *  如果 ids 存在子区域，则不允许删除
         * */
        for( Long id : ids ){
            LambdaQueryWrapper<TmsStoreGroupEntity> lqs = new LambdaQueryWrapper();
            lqs.eq(  TmsStoreGroupEntity::getParentId, id  );
            Integer count = tmsStoreGroupMapper.selectCount(lqs);
            if( count > 0){
                throw GlobalException.gen(11011, "请先删除子区域");
            }
        }

        if( !ObjectUtil.isNotEmptyList(ids) ){
            throw GlobalException.gen(10011, "要删除的id不存在");
        }
        tmsStoreGroupMapper.deleteBatchIds(ids);
    }

    @Override
    public void batchAddTmsStoreGroupByExcelFile(MultipartFile file) throws Exception {

        TmsStoreGroupListener listener = new TmsStoreGroupListener();
        EasyExcel.read(file.getInputStream(), TmsStoreGroupBatchAddVo.class,listener).sheet().doRead();;
        List<TmsStoreGroupBatchAddVo> list = listener.getList();
        //去数据库中查找是否存在
        System.out.println("storeGroupList:"+list);

        //先处理区
        Map<String, TmsStoreGroupEntity> map = new HashMap();
        List<TmsStoreGroupEntity> storeGroupListFromSql = tmsStoreGroupMapper.selectList(null);
        if( storeGroupListFromSql != null ){
            for(  TmsStoreGroupEntity item : storeGroupListFromSql ){
                map.put(item.getName(), item);
            }
        }

        // 处理 region
        for( TmsStoreGroupBatchAddVo item : list ){
            String regionName = item.getRegionName();
            if( map.get(regionName) == null ){

                String number = fmsCodeDictService.getCanUseCode(8);
                TmsStoreGroupVo tmsStoreGroupVo = new TmsStoreGroupVo();
                tmsStoreGroupVo.setNumber(number)
                        .setLevel(0)
                        .setName(regionName )
                        .setParentId(0L);

                TmsStoreGroupEntity newItem = this.addTmsStoreGroup(tmsStoreGroupVo);
                map.put(regionName, newItem);
            }
        }

        //处理 province
        for( TmsStoreGroupBatchAddVo item : list ) {
            //处理 province
            String regionName = item.getRegionName();
            String provinceName = item.getProvinceName();
            if( map.get(provinceName) == null ){

                TmsStoreGroupEntity parentItem = map.get(regionName);

                String number = fmsCodeDictService.getCanUseCode(8);
                TmsStoreGroupVo tmsStoreGroupVo = new TmsStoreGroupVo();
                tmsStoreGroupVo.setNumber(number)
                        .setLevel(parentItem.getLevel()+1)
                        .setName(provinceName)
                        .setParentId(parentItem.getId())
                        .setParentName(parentItem.getName());

                TmsStoreGroupEntity newItem = this.addTmsStoreGroup(tmsStoreGroupVo);
                map.put(provinceName, newItem);
            }
        }

        //处理市
        for( TmsStoreGroupBatchAddVo item : list ) {
            //处理 city
            String provinceName = item.getProvinceName();
            String cityName = item.getCityName();
            if( map.get(cityName) == null ){

                TmsStoreGroupEntity parentItem = map.get(provinceName);

                String number = fmsCodeDictService.getCanUseCode(8);
                TmsStoreGroupVo tmsStoreGroupVo = new TmsStoreGroupVo();
                tmsStoreGroupVo.setNumber(number)
                        .setLevel(parentItem.getLevel()+1)
                        .setName(cityName)
                        .setParentId(parentItem.getId())
                        .setParentName(parentItem.getName());

                TmsStoreGroupEntity newItem = this.addTmsStoreGroup(tmsStoreGroupVo);
                map.put(cityName, newItem);
            }
        }


        //处理县
        for( TmsStoreGroupBatchAddVo item : list ){
            //处理 area
            String cityName = item.getCityName();
            String areaName = item.getAreaName();
            if( map.get(areaName) == null ){
                TmsStoreGroupEntity parentItem = map.get(cityName);

                String number = fmsCodeDictService.getCanUseCode(8);
                TmsStoreGroupVo tmsStoreGroupVo = new TmsStoreGroupVo();
                tmsStoreGroupVo.setNumber(number)
                        .setLevel(parentItem.getLevel()+1)
                        .setName(areaName)
                        .setParentId(parentItem.getId())
                        .setParentName(parentItem.getName());

                TmsStoreGroupEntity newItem = this.addTmsStoreGroup(tmsStoreGroupVo);
                map.put(areaName, newItem);
            }

        }

    }

}

      